<?php

namespace app\api\controller\v1\store\lottery;

use app\admin\model\DataStoreBalanceLog;
use app\admin\model\DataStoreUser;
use app\admin\model\DataUserLotteryLog;
use app\admin\model\DataUserLotteryNum;
use app\admin\model\PaymentConfig;
use app\api\controller\Api;
use lslcoded\qrcode\QrCode;
use think\exception\HttpResponseException;
use think\Response;



class Draw extends Api
{

    protected $payment;
    protected $page;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $pay = new PaymentConfig();
        $pay = $pay->column('content')[0];
        $config = json_decode($pay,true);
        $this->payment = Pay::instance($config);
        $this->page = 'page/index';
    }


    public function get(){
        $list =$this->getModel()->where(['store_id'=>$this->user['id'],'win'=>1])->order('id desc')->findOrEmpty();
        if($list->isEmpty())$this->success('获取成功',[]);
        $win = $this->getModel()->with('user')->where(['batch'=>$list['batch']])->select();
        $this->success('获取成功',$win);
    }


    public function get_code_num(){
        $code = new DataUserLotteryNum();
        $store = new  DataStoreUser();
        $store = $store->with('lottery')->where(['unid'=>$this->user['id']])->findOrEmpty();
        if($store->isEmpty())$this->error('商铺不存在');
        $code = $code->whereNull('unid')->where(['store_id'=>$store->id])->findOrEmpty();
        if($code->isEmpty()) $this->error('二维码不存在');
        $content =  $this->page.$code['code']; // 二维码内容
        $save_code = new QRcode();
        $code_path =  $save_code->png($content)->getPath();
        $this->success('获取成功',[
            'code'=>$this->request->domain().$code_path
        ]);

    }

    public function get_code(){
        $rule = [
            'out_trade_no'    => 'require',
        ];
        $message  =   [
            'out_trade_no.require' => '订单号不为空',
        ];
        $this->validate($this->post, $rule, $message);
        $code = new DataUserLotteryNum();
        $store = new  DataStoreUser();
        $store = $store->with('lottery')->where(['unid'=>$this->user['id']])->findOrEmpty();
        if($store->isEmpty())$this->error('商铺不存在');
        $code = $code->whereNull('unid')->where(['store_id'=>$store->id])->findOrEmpty();
        if($code->isEmpty()) $this->error('二维码不存在');
        $content =  $this->page.$code['code']; // 二维码内容
        $save_code = new QRcode();
        $code_path =  $save_code->png($content)->getPath();
        $this->success('获取成功',[
            'code'=>$this->request->domain().$code_path
        ]);

    }



    public function set(){


        try {
            $rule = [
                'pay_type'    => 'require',   //1 余额  2微信
                'price'    => 'require',
            ];
            $message  =   [
                'pay_type.require' => '支付类型不为空',
                'price.require' => '支付金额不为空',
            ];
            $this->validate($this->post, $rule, $message);

            $store = new  DataStoreUser();
            $store = $store->with('lottery')->where(['unid'=>$this->user['id']])->findOrEmpty();
            if($store->isEmpty())$this->error('商铺不存在');
            $num = new DataUserLotteryNum();
            $num =$num->whereNull('unid')->where(['store_id'=>'store_id'])->findOrEmpty();
            if(!$num->isEmpty()) $this->error('二维码已存在');
            if($this->post['pay_type'] ==1){
                if(intval($store->balance) - intval($store->lottery['price'])<=0)$this->error('余额不足');
                $save = [
                    'pay_type'=>1,
                    'store_id'=>$store->id,
                    'type'=>1,
                    'status'=>1,
                    'real_price'=>$store->lottery['price'],
                    'price'=>$this->post['price'],
                ];
                $log = new DataStoreBalanceLog();
                $log->save($save);
                $code = new DataUserLotteryNum();
                $code = $code->whereNull('unid')->where(['store_id'=>$store->id])->column('code');
                $content =  $this->page.$code[0]; // 二维码内容
                $save_code = new QRcode();
                $code_path =  $save_code->png($content)->getPath();
                $this->success('获取成功',[
                    'code'=>$this->request->domain().$code_path
                ]);
            }elseif($this->post['pay_type'] ==2) {
                $order_no = 'P'.time();
                $options = [
                    'body' => '平台服务',
                    'out_trade_no' =>$order_no,
                    'total_fee' => intval($store->lottery['price']),
                    'openid' => $this->user['openid'],
                    'trade_type' => 'JSAPI',
                    'notify_url' => $this->request->domain().'/api/v1/notify',
                    'spbill_create_ip' => $this->request->ip()
                ];
                 $save = [
                     'pay_type'=>2,
                     'store_id'=>$store->id,
                     'out_trade_no'=>$order_no,
                     'type'=>1,
                     'status'=>0,
                     'real_price'=> $store->lottery['price'],
                     'price'=>$this->post['price'],
                 ];
                $log = new DataStoreBalanceLog();
                $log->save($save);
                $result = $this->payment->create($options);
                $result['out_trade_no'] = $order_no;
                $this->success('请求支付成功',$result);
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error("处理失败，{$exception->getMessage()}");
        }

    }


    /**
     * 支付通知处理
     */
    public function notify(array $data = [], ?array $notify = null): Response
    {

        $notify = $notify ?: $this->payment->getNotify();

        if ( $notify['result_code'] == 'SUCCESS' && $notify['return_code'] == 'SUCCESS') {
            $log = new DataStoreBalanceLog();
            $log->where(['out_trade_no'=> $notify['out_trade_no']])->save(['status'=>1,'remarks'=>json_encode($notify, 64 | 256)]);
        }
        return xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
    }



    public function pay_list(){
        $log = new  DataStoreBalanceLog();
        $store = new  DataStoreUser();
        $store = $store->with('lottery')->where(['unid'=>$this->user['id']])->findOrEmpty();
        if($store->isEmpty())$this->error('商铺不存在');
        $log =$log->where(['type'=>1,'store_id'=>$store->id])->select();
        $this->success('获取成功',$log);
    }


    public function getModel(){
        return new DataUserLotteryLog();
    }

}